<template>
  <div v-bind:style="styleObject" class="scale-box">
    <slot></slot>
  </div>
</template>

<script setup name="ScaleBox">
// import debounce from "lodash/debounce";
import { computed, reactive,ref, watch, onMounted,onUnmounted   } from "vue";
let that = reactive({
  width: 1920,
  height: 1080,
  scaleX: null,
  scaleY: null,
});
let styleObject = computed(() => {
  let obj = {
    transform: `scale(${that.scaleX},${that.scaleY}) translate(-50%, -50%)`,
    WebkitTransform: `scale(${that.scaleX},${that.scaleY}) translate(-50%, -50%)`,
    width: that.width + "px",
    height: that.height + "px",
  };
  return obj;
});

const getScale = () => {
  // 分别计算X轴和Y轴的缩放比例
  that.scaleX = window.innerWidth / that.width;
  that.scaleY = window.innerHeight / that.height;
};

const setScale = debounce(() => {
  // 获取到缩放比，设置它
  getScale();
}, 200);
function debounce(fn, delay) {
  const delays = delay || 500;
  let timer;
  return function () {
    const th = this;
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delays);
  };
}
onMounted(() => {
  getScale();
  window.addEventListener("resize", setScale);
});

onUnmounted(() => {
  window.addEventListener("resize", setScale);
});
</script>

<style lang="scss" scoped>
.scale-box {
  transform-origin: 0 0;
  position: absolute;
  left: 50%;
  top: 50%;
  transition: 0.1s;
}
</style>
